package com.hmkj.core.api.ufx.call;

import com.hmkj.core.api.ufx.mc.UFXMC;
import com.hmkj.core.api.ufx.trade.UfxTradeSync;
import com.hmkj.core.model.quote.TrendData;
import com.hundsun.mcapi.MCServers;
import com.hundsun.t2sdk.impl.client.T2Services;
import com.xiaoleilu.hutool.date.DateUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 期货行情相关请求实例
 */
public class QuotationCall {

    private static T2Services server = T2Services.getInstance();//T2实例化

    private static UFXMC ufxmc = new UFXMC();

    private static UfxTradeSync ufxTradeSync = new UfxTradeSync();

    private static QuotationCall quotationCall = new QuotationCall();

    private static Map<String, List<String>> tenderTimeMap;


    public static QuotationCall getInstance() {
        return quotationCall;
    }

    /**
     * 获取T2SDK配置文件中配置的连接
     * 启动T2SDK，只需要在服务器启动时调用一次就可以了
     */
    public void initT2() throws Exception {
        server.setT2sdkConfigString("classpath:config/t2sdk_hundsun_quote-config.xml");//配置文件路径
        server.init();
        server.start();
        MCServers.MCInit();
    }

    /**
     * 断开服务
     */
    public void stop() {
        server.stop();
    }

    /**
     * 行情主推订阅
     */
    public void reqSubQuotation() {
        // 订阅国际期货行情
        ufxmc.reqFunctionSubQuoOut();
        // 订阅国内期货行情
        ufxmc.reqFunctionSubQuoIn();

    }

    /**
     * 查询国际期货分时行情
     *
     * @param futuExchType  交易所
     * @param commodityType 品种代码
     * @param contractCode  合约号
     * @param requestNum    请求条数
     * @return List<TrendData>
     */
    public List<TrendData> getTrendDataOut(String futuExchType, String commodityType, String contractCode, String requestNum) throws Exception {
        ufxTradeSync.Init();
        String result = ufxTradeSync.ReqFunction800050(futuExchType, commodityType, contractCode, requestNum);
        //返回信息如下：
        /*
            contract_code,futu_exch_type,commodity_type,min_time,date,last_price,average_price,business_amount,business_balance,min_amount,
            1709,NYMEX,CL,2222,20170817,46.850000,46.710000,268373,12535712.740000,1025,
         */
        String[] data = result.split("\n");
        List<TrendData> trendDataList = new LinkedList<>();
        for (int i = data.length - 1; i > 0; i--) {
            String[] args = data[i].split(",");
            TrendData trendData = new TrendData();
            trendData.setCc(args[0]);
            trendData.setFet(args[1]);
            trendData.setCt(args[2]);
            trendData.setMt(args[3]);
            trendData.setD(args[4]);
            trendData.setNp(args[5]);
            trendData.setAp(args[6]);
            trendData.setBa(args[7]);
            trendData.setBb(args[8]);
            trendData.setMa(args[9]);
            trendData.setHp(args[10]);
            trendData.setLp(args[11]);
            trendData.setOp(args[12]);
            trendData.setCp(args[13]);
            trendDataList.add(trendData);
        }
        return trendDataList;
    }

    /**
     * 查询国内期货分时行情
     *
     * @param commodityType 品种代码
     * @param contractCode  合约号
     * @return List<TrendData>
     */
    public List<TrendData> getTrendDataIn(String commodityType, String contractCode) throws Exception {
        ufxTradeSync.Init();
        String result = ufxTradeSync.ReqFunction3003(commodityType + contractCode);
        //返回信息如下：
        /*
            last_price,business_amount,
            46.850000,46,
         */
        String[] data = result.split("\n");
        List<TrendData> trendDataList = new LinkedList<>();
        SimpleDateFormat f1 = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat f2 = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date();
        String dateStr = f2.format(now);
        List<String> tenderTimeList = tenderTimeMap.get(commodityType);

        String preDateStr = f2.format(DateUtil.offsetDay(now, -1));

        // 前分时点总量
        long pba = 0L;

        for (int i = 1; i < data.length; i++) {
            String[] args = data[i].split(",");
            TrendData trendData = new TrendData();
            trendData.setCc(contractCode);
            trendData.setCt(commodityType);
            trendData.setNp(args[0]);
            trendData.setBa(args[1]);

            trendData.setD(dateStr);
            trendData.setMt(tenderTimeList.get(i - 1));
            if (DateUtil.offsetMinute(now, 1).before(f1.parse(dateStr + trendData.getMt()))) {
                trendData.setD(preDateStr);
            }
            trendData.setDt(f1.parse(trendData.getD() + trendData.getMt()).getTime());

            trendData.setMa(String.valueOf(Long.parseLong(args[1]) - pba));

            trendDataList.add(trendData);

            pba = Long.parseLong(trendData.getBa());
        }


//        // 总量
//        long totalVol = 0L;
//        // 总金额
//        BigDecimal totalBalance = BigDecimal.ZERO;
//        List<TrendData> datas = new ArrayList<>();
//        for (int i = trendDataList.size() - 1; i >= 0; i--) {
//            TrendData item = trendDataList.get(i);
//            // 分时量
//            long curVol = Long.parseLong(item.getBa()) - totalVol;
//            item.setBa(String.valueOf(curVol));
//            // 分时成交金额
//            BigDecimal curBalance = new BigDecimal(item.getNp()).multiply(new BigDecimal(curVol));
//
//            totalVol = Long.parseLong(item.getBa());
//            totalBalance = totalBalance.add(curBalance);
//            // 计算均价
//            BigDecimal avgPrice = totalBalance.divide(new BigDecimal(totalVol), 2, BigDecimal.ROUND_HALF_UP);
//            item.setAp(String.valueOf(avgPrice));
//            datas.add(item);
//
//        }
        return trendDataList;
    }

    public void qryMarket() throws Exception {
        ufxTradeSync.Init();
        String result = ufxTradeSync.ReqFunction3007();
        System.out.println(result);

    }

}
